<template>
  <div id="rtuCtrl" class="wrapper" style="overflow:hidden;">
    <div class="py-3 pl-5" style="border-bottom: 1px solid #c4c4c4">
      <label>RTU分组：</label>
      <el-select class="w140" size="small" v-model="rtuGroup" @change="changeGroup">
        <el-option label="无分组" value=""></el-option>
        <el-option v-for="(item,index) in rtuGroups" :key="index" :label="item.GroupName" :value="item.Id+''"></el-option>
      </el-select>

      <div class="progress mr-3  w200 d-inline-block float-right" style="margin-top: 10px;">
        <div ref="progressBar" class="progress-bar progress-bar-striped" role="progressbar" style="width:0" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100"></div>
      </div>
    </div>
    <div>
      <!--rtu表格-->
      <div class="float-left p-3" >
        <el-table ref="rtuTable"  :data="rtus" style="width: 550px;" :height="350" highlight-current-row @selection-change="selsChange" >
          <el-table-column type="selection" width="30"></el-table-column>
          <!--<el-table-column align="center" type="index" :index="indexMethod" label="序号" width="50"></el-table-column>-->
          <el-table-column  align="center" prop="No" label="编号" width="130"></el-table-column>
          <el-table-column  align="center" prop="DevAddr" label="RTU" width="160"></el-table-column>
          <el-table-column  width="80" align="center" prop="result" label="下发结果" >
            <template slot-scope="scope">
              <span v-if="scope.row.result===1"><i class="circle success" ></i>成功</span>
              <span v-else-if="scope.row.result===0"><i class="circle error" ></i>失败</span>
              <span v-else>{{scope.row.result}}</span>
            </template>
          </el-table-column>
          <el-table-column  align="center" prop="resultInfo" label="失败原因" ></el-table-column>
        </el-table>
      </div>
      <!--回路信息-->
      <div class="float-left p-3 "  style="border-left: 1px solid #c4c4c4;width: 320px;height: 380px;">
        <ul class="loop-group">
          <li v-for="(item,index) in loops" :key="index" :class="{'disabled':switchState(index+1)}">
            <label class="pl-4" style="width: 45%"><el-checkbox v-model="item.isCheck" :disabled="switchState(index+1)">第{{item.name}}路</el-checkbox></label>
            <label style="width: 30%"><el-radio v-model="item.onOff" :label="1" :disabled="switchState(index+1)">开灯</el-radio></label>
            <label><el-radio v-model="item.onOff" :label="0" :disabled="switchState(index+1)">关灯</el-radio></label>
          </li>
        </ul>
        <div class="d-flex mt-4">
          <div class="">
            <label >操作密码：</label>
            <el-tooltip class="item" :content="errors.first('pwd')" :value="errors.has('pwd')" :manual="true">
              <el-input type="password" size="small" class="w120" v-model="operatePwd" v-validate="'required'" name="pwd"></el-input>
            </el-tooltip>
          </div>
          <!--:class="{'ur-btn-primary':!btnState}"-->
          <el-button class="ur-btn w75 ml-2"  type="info ur-btn-primary" @click="callFun" :disabled="btnState"><i class="iconfont icon-queding"></i>下发</el-button>
        </div>
      </div>
    </div>

  </div>
</template>

<script type="text/ecmascript-6">
  import api from 'api/api'
  import fetch from 'api/fetch'

  export default {
    components: {},
    props: {
      boxs:{
        type:Array,
        default:function () {
          return []
        }
      },
    },
    data() {
      return {
        rtuGroup:'',
        boxIds:[],
        loops:[
          {name:'一',isCheck:false,onOff:0},
          {name:'二',isCheck:false,onOff:0},
          {name:'三',isCheck:false,onOff:0},
          {name:'四',isCheck:false,onOff:0},
          // {name:'五',isCheck:false,onOff:0},
          // {name:'六',isCheck:false,onOff:0},
          // {name:'七',isCheck:false,onOff:0},
          // {name:'八',isCheck:false,onOff:0},
        ],
        switchNos:[],
        operatePwd:'',
        callNum:{total:0,success:0,error:0},
        btnState:false,
        rtus:this.boxs,
        outlineNum:0,
        rtuGroups:[]
      }
    },
    watch: {
      // sels(boxs){
      //   boxs.map(box=>{
      //     this.$refs.rtuTable.toggleRowSelection(box)
      //   })
      // }
    },
    computed: {
    },
    methods: {
      indexMethod(index) {
        return index + 1
      },
      changeGroup(id){
        if(id==''){
          this.rtus=this.boxs
        }else{
          api.fetchSimple('/Group/GetRtuByGroup',{groupId:id,value:''})
            .then(r=>{
              this.rtus=r.data
            })
        }
      },
      selsChange(sels) {
        this.sels = sels
        this.sels.splice(0,0)
        this.getOutlineNum()
      },
      callFun(){
        this.$validator.validateAll().then((res) => {
          let pIndex = 1
          let boxIds=[]
          if (res) {
            let switchs=[]
            this.loops.map((v,index,arr)=>{
              if (v.isCheck) switchs.push({SwitchNo: index + 1, CtlType: v.onOff})
            })
            if (switchs.length == 0) return this.$message.warning('请选择线路')
            this.$store.commit('user/SET_USER_PWD', this.operatePwd)
            this.sels.map(box => {
              boxIds.push(box.BoxId)
              box.result = '正在控制中...'
              api.fetch('/Communication/Rtu/RtuSwitchController?devAddr=' + box.DevAddr, switchs)
                .then(r => {
                  this.btnState=true
                  box.opereaTime=api.formatDate(new Date(),'yyyy-MM-dd HH:mm:ss')
                  if (r.err) {
                    this.callNum.error = this.callNum.error + switchs.length
                    box.result = 0
                    box.resultInfo = r.err
                  } else {
                    this.callNum.success = this.callNum.success + switchs.length
                    box.result = 1
                    box.resultInfo = '/'
                  }
                  let total = this.sels.length
                  let pcen = Math.round(pIndex / total * 100) > 100 ? 100 : Math.round(pIndex / total * 100)
                  // this.$emit('updateBar',pcen)
                  this.$refs.progressBar.style.width = pcen + '%'
                  this.$refs.progressBar.textContent = pcen + '%'
                  pIndex++
                  if (pcen==100) {
                    // this.callNum.total = this.callNum.error + this.callNum.success
                    // this.$emit('updateResult',{callNum:this.callNum,boxIds:boxIds})
                    this.btnState=false
                    this.rtus.splice(0,0)
                  }
                })
            })
          }
        })
      },
      getRtuGroup(){
        api.fetchSimple('/Group/QueryLikeRtu',{})
          .then(r=>{
            this.rtuGroups=r.data
          })
      },
      switchState(index){
        // return this.switchNos.indexOf(index)==-1
        if (this.outlineNum < index) {
          return true
        }
      },
      getOutlineNum(){
        this.outlineNum=0
        this.sels.map(box => {
          let num=box.OutlineNum?box.OutlineNum:0
          if (num > this.outlineNum) {
            this.outlineNum = num
          }
        })
      },
      querySwitch(){
        this.sels.map(box=>{
          fetch.querySwitch({BoxId:box.BoxId})
            .then(r=>{
              let data=r.data
              data.map(r=>{
                if (this.switchNos.indexOf(r.SwitchNo) == -1) {
                  this.switchNos.push(r.SwitchNo)
                }
              })
            })
        })
      },
      queryRtuInfo(){
        let _this=this
        api.fetchSimple('/Manual/QueryRtuCtlInfo',{queryType:1,value:''})
          .then(r => {
            _this.rtus = r.data
            if(r.data.length){
              (r.data).map(r=>{
                r['result']=''
              })
            }
          })
      },
    },
    created() {
      this.getRtuGroup()
      this.boxs.map(r=>{
        r['result']=''
        r['resultInfo']=''
      })
      // this.queryRtuInfo()
    },
    mounted() {
    },
    activated(){

    }
  }
</script>
<style scoped lang="stylus" rel="stylesheet/stylus">
  .loop-group{
    li{border: 1px solid #ddd;border-radius: 4px;height: 44px;line-height: 44px;margin-bottom: 10px;
      &.disabled{cursor: not-allowed;}
    }
  }
</style>
